/**
 * @author helio
 */
var IncomeInputView = Ext.extend(BasicPanel,{
	
	selectedAccountInfo : null,
	
	initlize : function() {
		
		if(!this.inputForm) {
			this.inputForm = new Ext.FormPanel({
				region:'north',
				autoHeight: true,
				labelWidth: 55,
				margins: '5 5 5 5',
				bodyStyle : 'background-color: transparent;', 
				defaultType: 'textfield',
								
				items: [{
					xtype:'fieldset',
					border: false,
					autoHeight:true,
					anchor:'100%',
					layout:'column',
									
					items: [{
						columnWidth:.5,
						layout: 'form',
						border:false,
						bodyStyle: 'padding-left:5px;background-color: transparent;',
						items: [{
							xtype:'textfield',
							fieldLabel: '编号',
						    name: 'code',
						    anchor:'95%'
						}, {
		                	xtype:'trigger',
		                    triggerClass: 'x-form-search-trigger',
		                    name: 'client',
		                    fieldLabel: '付款单位',
		                    anchor:'95%',
		                    onTriggerClick: function(){
								var pname = this.inputForm.form.findField("client").getValue();
			   					var condition = {querytype:2,queryvalue:pname};
			   					SALE.window.showClientSelectWindow(this.clientSelectedHandler.createDelegate(this),condition);
				       		}.createDelegate(this)
		                }]
					},{
						columnWidth:.5,
						layout: 'form',
						border:false,
						bodyStyle: 'background-color: transparent;',
						items: [{
							xtype:'datefield',
						    fieldLabel: '录单日期',
						    name: 'entry_date',							
							format:'Y-m-d',
						    anchor:'65%'
						}, new Ext.form.ComboBox({
							tpl: comboxTpl,
							fieldLabel: '经办人',
					        store: DataStoreUtil.getUserStore(),
					        displayField:'name',
					        typeAhead: true,
					        mode: 'local',
					        forceSelection: false,
					        triggerAction: 'all',
					        emptyText:'选择或输入经办人...',
					        selectOnFocus:true,
							name: 'operator',
							
							anchor:'65%'
					    }),{
						    xtype:'textfield',
						    fieldLabel: '摘要',
						    name: 'comment',
						    anchor:'95%'
						}]
					}]
				}]
			});
		}	
		
		
		if(!this.detailsGrid) {
			
			this.initDetailsJson();
			
			this.detailsStore = new Ext.data.Store({
			    proxy: new Ext.data.MemoryProxy(this.detailsJson),
			    reader: new Ext.data.JsonReader({
					root: 'details',
					remoteSort: true,
		            fields: ['id','acode','aname', {name:'aamount', type: 'float'}, 'acomment']
				})
			});
			
			this.detailsStore.load();
			
			this.detailsGrid = new Ext.grid.EditorGridPanel({
				region:'center',
				store: this.detailsStore,
				viewConfig: {
			        forceFit: true,
					enableRowBody:true,
		            showPreview:true
			    },
		
				stripeRows: true,
				margins: '5 5 5 5',
				border: true,
				autoExpandColumn: 'aname',
				
				columns: [new Ext.grid.RowNumberer(),{
	           		header: "收款帐户编号",
	           		dataIndex: 'acode',
	           		width: 100,
	           		editor: new Ext.form.ComboBox({
							tpl: comboxTplCode,
					        store: DataStoreUtil.getBankAccountStore(),
					        displayField:'code',
					        typeAhead: true,
					        mode: 'local',
					        forceSelection: false,
					        triggerAction: 'all',
					        selectOnFocus:true,
							listeners: {
								'select': this.slectAccountHandler.createDelegate(this)
							},
							anchor:'100%'
					    })
	       		},{
	           		header: "收款帐户名称",
	           		dataIndex: 'aname',
	           		align: 'left',
	           		editor: new Ext.form.ComboBox({
							tpl: comboxTpl,
					        store: DataStoreUtil.getBankAccountStore(),
					        displayField:'name',
					        typeAhead: true,
					        mode: 'local',
					        forceSelection: false,
					        triggerAction: 'all',
					        selectOnFocus:true,
							listeners: {
								'select': this.slectAccountHandler.createDelegate(this)
							},
							anchor:'100%'
					    })
	        	},{
	           		header: "金额",
	           		dataIndex: 'aamount',
	           		width: 70,
	           		align: 'right',
	           		editor: new Ext.form.NumberField({
	               		allowBlank: false,
	               		allowNegative: false
	           		})
	        	},{
	           		header: "备注",
	           		dataIndex: 'acomment',
	           		width: 80,
	           		align: 'left',
	           		editor: new Ext.form.TextField({
		            	allowBlank: true
		            })
	        	}],
				
				listeners: {
					'afteredit': this.aftereditHandler.createDelegate(this),
					'afterrender': function(){
						var store = this.detailsGrid.store;
						Ext.getCmp("totalAmount").setValue(store.sum("aamount"));
					}.createDelegate(this)
				},
				
				bbar: [{
					text:''
				}, "->", "-", "合计金额：", {
					xtype:'numberfield',
					id : 'totalAmount',
					renderer: Ext.util.Format.numberRenderer('0,000.00'),
					width:200
				}, "-"],
								
				buttons: [{
					text: '保存',
					listeners: {
						"click": this.saveHandler.createDelegate(this)
					}
				},{
					text: '取消',
					listeners:{
						"click":this.cancelHandler.createDelegate(this)
					}
				}]
			});
		}
			
	},
	
	getCorePanel : function() {
		this.corePanel = new Ext.Panel({
			title: '其它收入',
			border: false,
			layout: 'border',
			
			items: [this.inputForm, this.detailsGrid]
		});
		if(this.task == 'new') {
			SALE.Action.codeGenerator(this.setCode.createDelegate(this),"SR");
		}
		return this.corePanel;
	},
	
	slectAccountHandler : function(combox, record, index) {
		combox.value = record.data.name;		
		this.selectedAccountInfo = record;
	},
	
	aftereditHandler : function(grid) {
		var record = grid.record;//获取被修改的行
	    var field = grid.field;//获取被修改的列
	    
	    if((field == "acode" || field == "aname") && this.selectedAccountInfo) {
			record.set("acode", this.selectedAccountInfo.data.code);
			record.set("aname", this.selectedAccountInfo.data.name);
		}
							
		if(field == "aamount") {
			var store = this.detailsGrid.store;
			Ext.getCmp("totalAmount").setValue(store.sum("aamount"));
		}
	},
	
	saveHandler : function() {
		
		var form = this.inputForm.form;
		var billJson = {};
		if(this.formDataJson &&this.formDataJson.id) {
			billJson = {id: this.formDataJson.id};
		}
		
		for(var i = 0; i < form.items.items.length; i++){
			var field = form.items.items[i];
			if(field.isFormField) {			
				billJson[field.name] = field.getValue();
			}		
		}
		
		var details = [];	
		var store = this.detailsGrid.store;
		var records = store.getRange(0, store.getTotalCount());
		for(var i=0;i<records.length;i++) {
			if(records[i].data.acode) {
				var record = records[i];		
				details[i] = record.data;	
			}			
		}
		
		billJson["details"] = details;
		
		if(details.length > 0) {
			billJson["amount"] = Ext.getCmp("totalAmount").getValue();
			billJson["type"] = "2";
			
			//show the load mask.
			SALE.Utils.showLoadMask(this.corePanel);
			
			SALE.Action.savePaymentInfo(this.saveBillSuccessHandler.createDelegate(this), billJson, this.task);
		}		
	},
	
	confirmDirectly : function(record) {
		var confirmArray = [{
			id: record['id'],
			code: record['code'],
			confirm_status: '1'
		}];
		this.task = 'confirm';
		SALE.Action.savePaymentInfo(this.saveBillSuccessHandler.createDelegate(this), confirmArray, "confirm");
	},
	
	saveBillSuccessHandler : function(record) {
		//hide the load mask
		SALE.Utils.hideLoadMask();
		
		if(this.task == 'new' || this.task == 'auto') {
			Ext.MessageBox.show({
	            title:'添加成功！',
	            msg: '收款单添加成功！ <br/><br/>选择"继续添加"可继续添加新的收款单。',
	            buttons:{"yes":"继续添加","no":"结账确认"},
	            fn: function(btn) {
					if (btn == "yes") {
						IncomeInputView.showInputPanel(null, this.task);
					} else if(btn == "no") {
						this.confirmDirectly(record)
					}
				}.createDelegate(this),
				closable:false,
	            icon: Ext.MessageBox.QUESTION
	        });
		} else if(this.task == 'confirm') {
			this.task = 'new';
			Ext.MessageBox.show({
	            title:'账单确认成功！',
	            msg: '账单确认成功！ <br/><br/>选择"继续添加"可继续添加新的收款单。',
	            buttons:{"yes":"继续添加","no":"确定"},
	            fn: function(btn) {
					if (btn == "yes") {
						IncomeInputView.showInputPanel(null, this.task);
					} 
				}.createDelegate(this),
				closable:false,
	            icon: Ext.MessageBox.QUESTION
	        });
		} else {
			this.showMessage("收款单修改成功！！！");
		}		
	},
	
	cancelHandler : function() {
		this.clear();
		this.clearGrid();
		Ext.getCmp("totalAmount").setValue(0);
	},
	
	clientSelectedHandler: function(record) {
		this.inputForm.form.findField("client").setValue(record.get("name"));
	},
	
	initDetailsJson: function() {
		if(!this.detailsJson || !this.detailsJson.details) {
			this.detailsJson = {details: []};
		}
		if(this.detailsJson.details.length < 30) {
			for(var i = this.detailsJson.details.length; i < 30; i++) {
				this.detailsJson.details.push({
					acode: "",
					aname: "",
					aamount: "",
					acomment: ""
				});
			}
		}
	}
});

IncomeInputView.showInputPanel = function(initData, task) {
	var details;
	
	if(!initData) {
		initData = {
			'entry_date' : new Date(),
			'operator' : SALE.App.userInfo.name
		};
		if (SALE.App.loginType === "local") {
			initData.code = SALE.Utils.createBillCode("SR");			
		}			
		task = 'new';
	} else {
		task = !task ? 'modify' : task;
	}
	
	var inputView = new IncomeInputView({
		task : task,
		formData: initData,
		details: {
			details: initData.details
		}
	});
	inputView.initlize();
	
	if (task == 'modify') {
		SALE.App.showNextOperateTabPanel(inputView.getCorePanel(), "修改收款单");
	} else if(task == 'auto') {
		SALE.App.showNextOperateTabPanel(inputView.getCorePanel(), "添加收款单");
	} else {
		SALE.App.showOperateTabPanel(inputView.getCorePanel(), "添加收款单");
	}
	inputView.synchronizeForm();
}
